/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.srwl.mytx.Constant;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.contrack.LoginConstrack;
import com.srwl.mytx.contrack.LoginPresenterImpl;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.Utils;
import com.starrtc.starrtcsdk.api.XHClient;


/**
 * Login screen
 */
public class LoginActivity extends BaseActivity implements LoginConstrack.View {
    public static void startActivity(Context activity, String extraData) {
        activity.startActivity(new Intent(activity, LoginActivity.class).putExtra("EXTRA_CONTENT", extraData));
    }

    private static final int REQUEST_CODE = 1;
    private EditText et_phone;
    private EditText et_password;

    private boolean autoLogin = false;
    private String phone;
    private String password;
    private Button btn_login;
    private ImageView btn_aliLogin;
    private Button btn_register;
    private TextView tv_forgetPassWord;
    private Context context;
    private LoginConstrack.Presenter presenter;
    private ImageView iv_hide;
    private ImageView iv_show;
    private TextView tv_third_login;
    private ProgressDialog progressDialog;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;
    private boolean fromTempUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBroadcast();
        context = this;
        // enter the main activity if already logged in
//        if (Helper.getInstance().isLoggedIn()) {
//            autoLogin = true;
//            startActivity(new Intent(LoginActivity.this, MainActivity.class));
//            return;
//        }
        setContentView(R.layout.activity_login);
        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.password);
        btn_register = findViewById(R.id.btn_register);
        btn_login = findViewById(R.id.btn_login);
        btn_aliLogin = findViewById(R.id.btn_ali_login);
        tv_forgetPassWord = findViewById(R.id.tv_forget_pass_word);
        tv_third_login = findViewById(R.id.tv_third_login);
        iv_hide = findViewById(R.id.iv_hide);
        iv_show = findViewById(R.id.iv_show);
        tv_third_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_third_login.setVisibility(View.GONE);
                btn_aliLogin.setVisibility(View.VISIBLE);
            }
        });
        iv_hide.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_hide.setVisibility(View.INVISIBLE);
                iv_show.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(HideReturnsTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }

            }

        });
        iv_show.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_show.setVisibility(View.INVISIBLE);
                iv_hide.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(PasswordTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
            }

        });


        initTextChangeListener();

        String loginRecordPhoneNumber = UserProfileManager.getInstance().getUserPhoneNumber();
        if (!TextUtils.isEmpty(loginRecordPhoneNumber)) {
            et_phone.setText(loginRecordPhoneNumber);
        }


        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
        btn_aliLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.alipayAuthUrl();
            }
        });
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(LoginActivity.this, RegisterActivity.class), REQUEST_CODE);
            }
        });
        tv_forgetPassWord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, ReplacePassWordActivity.class));
            }
        });
        initProgressDialog();
        setPresenter(new LoginPresenterImpl(this, context));
        Helper.getInstance().checkUpdate(this);
        fromTempUser = Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo());
        String content = getIntent().getStringExtra("EXTRA_CONTENT");
        if (!TextUtils.isEmpty(content)) {
            TextView tv_extraContent = findViewById(R.id.tv_extra_content);
            tv_extraContent.setText(content);
        }
    }

    private void initTextChangeListener() {
        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_phone.getCurrentTextColor() == Color.RED) {
                    et_phone.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_password.getCurrentTextColor() == Color.RED) {
                    et_password.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    private void login() {
        hideSoftKeyboard();
        phone = et_phone.getText().toString().trim();
        password = et_password.getText().toString().trim();

        if (TextUtils.isEmpty(phone)) {
//            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
//                showToast(btn_login, "手机号不能为空");
//            } else {
//
//            }
            et_phone.setHint("手机号不能为空");
            Utils.editViewValueErrorAnimate(et_phone, context);
            et_phone.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少魅蓝4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (!Utils.checkMobileNum(phone)) {
            btn_login.setEnabled(true);
            et_phone.setTextColor(Color.RED);
            showToast(btn_login, "输入的手机号格式有误，请重新输入");
            Utils.editViewValueErrorAnimate(et_phone, this);
            return;
        }

        if (TextUtils.isEmpty(password)) {
//            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
//                showToast(btn_login, "密码不能为空");
//            } else {
//
//            }
            et_password.setHint("密码不能为空");
            Utils.editViewValueErrorAnimate(et_password, context);
            et_password.setPadding(Utils.dpToPx(90, context), 0, 0, 0);
            return;
        }

        if (password.length() < 6) {
            showToast(btn_login, "密码不足6位");
            // et_password.setError("密码不足6位");
            et_password.setTextColor(Color.RED);
            Utils.editViewValueErrorAnimate(et_password, context);
            return;
        }
        // DemoDBManager.getInstance().closeDB();
        //其实在登出的时候已经关闭了一次，这儿还用得着再关一次？？
        // DBManager.getInstance().closeDB();
        // reset current user name before login
        // Helper.getInstance().getUserProfileManager().setUserPhoneNumber(phone);

//        broadcastManager.unregisterReceiver(broadcastReceiver);
//        //如果阿里云旺本来是登录状态，先退出，否则在更换用户又没有登出的情况下进行登录操作，会报错，无法登录
//        YWIMCore imCore = AliHelper.getInstance().getImCore();
//        IYWLoginService loginService = imCore.getLoginService();
//        if (imCore.getLoginState() == YWLoginState.success) {
//            loginService.logout(null);
//        }

        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        presenter.login(user);

    }


    @Override
    protected void onResume() {
        super.onResume();
        if (autoLogin) {
            return;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && !Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
            Intent backHome = new Intent(Intent.ACTION_MAIN);
            backHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            backHome.addCategory(Intent.CATEGORY_HOME);
            startActivity(backHome);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void setPresenter(LoginConstrack.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showToast(String message) {
        super.showToast(btn_login, message);
    }

    @Override
    public void showProgressDialog(String message) {
        progressDialog.setMessage(message);
        progressDialog.show();
    }

    @Override
    public void disMissProgressDialog() {
        progressDialog.dismiss();
    }

    @Override
    public void showLoginSuccess() {

        onRegisterOrLoginSuccess();

    }

    @Override
    public void showPasswordError() {
        et_password.setTextColor(Color.RED);
    }

    @Override
    public void showRetrievePassWord() {
        if (!tv_forgetPassWord.isShown()) {
            tv_forgetPassWord.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setLoginButtonStatus(final boolean bool) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn_login.setEnabled(bool);
            }
        });
    }

    public void initProgressDialog() {
        progressDialog = new ProgressDialog(context);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    }

    /**
     * 自动登录广播接收
     */
    private void initBroadcast() {
        broadcastManager = LocalBroadcastManager.getInstance(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_AUTO_LOGIN_SUCCESS);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == REQUEST_CODE) {
            boolean registerSuccess = data.getBooleanExtra("register_success", false);
            if (registerSuccess) {
                onRegisterOrLoginSuccess();
            }
        }
    }

    /**
     * 如果是临时用户跳转到登录页面，登录或者注册成功，需要广播出去，
     */
    private void onRegisterOrLoginSuccess() {

        if (fromTempUser) {
            finish();
             XHClient.getInstance().getLoginManager().logout();
            Helper.getInstance().onAccountChange();
        } else {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                IMSClientBootstrap.getInstance().login();
                try {
                    Thread.sleep(2000);//睡眠2s 是为了 避免startRTC 在调用登录后，立马调用初始化并登录，出问题，消息发不出去，，，
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Helper.getInstance().initStarRtc(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                Helper.getInstance().starRtcLogin();
            }
        }).start();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        broadcastManager.unregisterReceiver(broadcastReceiver);
        progressDialog.dismiss();
    }


}
